import jwt from 'jsonwebtoken';
import logger from '../config/logger.js';

const { JWT_SECRET = 'your-super-secret-jwt-key-for-development-change-in-production', JWT_EXPIRES_IN = '7d' } = process.env;

/**
 * 生成JWT令牌
 * @param {Object} payload - 要编码的数据
 * @param {string} [expiresIn=JWT_EXPIRES_IN] - 过期时间
 * @returns {string} JWT令牌
 */
export const signToken = (payload, expiresIn = JWT_EXPIRES_IN) => {
  try {
    return jwt.sign(payload, JWT_SECRET, { expiresIn });
  } catch (error) {
    logger.error('生成JWT令牌失败:', error);
    throw new Error('生成令牌失败');
  }
};

/**
 * 验证JWT令牌
 * @param {string} token - JWT令牌
 * @returns {Object} 解码后的令牌数据
 */
export const verifyToken = (token) => {
  try {
    return jwt.verify(token, JWT_SECRET);
  } catch (error) {
    logger.error('验证JWT令牌失败:', error.message);
    throw new Error('无效的令牌');
  }
};

/**
 * 从请求头中提取JWT令牌
 * @param {Object} req - Express请求对象
 * @returns {string} JWT令牌
 */
export const getTokenFromHeader = (req) => {
  let token = '';
  
  // 从Authorization头获取令牌
  if (req.headers.authorization && req.headers.authorization.startsWith('Bearer')) {
    token = req.headers.authorization.split(' ')[1];
  } 
  // 从cookie获取令牌
  else if (req.cookies && req.cookies.token) {
    token = req.cookies.token;
  }
  
  return token;
};

/**
 * 创建发送给客户端的令牌响应
 * @param {Object} user - 用户对象
 * @param {number} statusCode - HTTP状态码
 * @param {Object} res - Express响应对象
 * @returns {Object} 响应对象
 */
export const createSendToken = (user, statusCode, res) => {
  const token = signToken({ id: user.id, role: user.role });
  const cookieExpiresIn = process.env.JWT_COOKIE_EXPIRES_IN || 7;
  const cookieOptions = {
    expires: new Date(
      Date.now() + cookieExpiresIn * 24 * 60 * 60 * 1000
    ),
    httpOnly: true,
    secure: process.env.NODE_ENV === 'production',
  };

  // 移除密码字段
  user.password = undefined;

  res.status(statusCode).cookie('token', token, cookieOptions).json({
    success: true,
    token,
    data: {
      user,
    },
  });
};
